package session;
/*
 * 浏览器关闭后还能记住session的值
 */

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CountVisitTimesWithSession2CookieServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		//session.setMaxInactiveInterval(10);
		Integer count = (Integer) session.getAttribute("count");
		if(count==null){
			count=1;
		}else{
			count++;
		}
		session.setAttribute("count", count);
		
		PrintWriter out = response.getWriter();
		out.print("it's "+count+" times you visit.");
		out.print("sessionId:"+session.getId());
		//JSESSIONID is generated by tomcat server,other servers may not be the same,the follow is not a general way
		Cookie cookie = new Cookie("JSESSIONID", session.getId());
		cookie.setMaxAge(120);
		cookie.setPath(request.getContextPath());
		System.out.println(request.getContextPath());
		response.addCookie(cookie);
	}
}
